package com.coolgor.airvow.File;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;

public class FileIO {
	
	public static String read(String fileName,String encoding)
	{
		String res = "";
        try
        {
            InputStream r = new FileInputStream (fileName);
            ByteArrayOutputStream byteout = new ByteArrayOutputStream();
            byte tmp [] = new byte [r.available()];
            byte context [];
            int i = 0;
            while ((i=r.read(tmp))!=-1)
            {
               byteout.write(tmp);
               tmp = new byte [1024];
            }
            context = byteout.toByteArray();
            res = new String(context,encoding);
            String stra [] = res.split("\r");
//            for ( int n = 0; n < stra.length; n++ )
//            {
//                System.out.println(stra[n]);
//            }
        }  catch  (Exception e)
        {
            System.err.println(e);
        }
        return res;
	}
	
	public static String read(String fileName )
	{
        return read(fileName,"utf-8");
	}
	
	public static boolean write(String fileName, String content, String encoding, int reWrite)
	//reWrite —— 0:append; 1:rewrite.
	{
		String s = new String();
		String s1 = new String();
		try {
			File f = new File(fileName);
			if (f.exists()) {
				System.out.println("文件'"+fileName+"'存在");
				if (reWrite==1){
					f.delete();
					f.createNewFile();
				}
			} else {
				System.out.println("文件'"+fileName+"'不存在，正在创建...");
				if (f.createNewFile()) {
					System.out.println("文件'"+fileName+"'创建成功！");
				} else {
					System.out.println("文件'"+fileName+"'创建失败！");
			    }
			}
			BufferedReader input = new BufferedReader(new FileReader(f));
		
			while ((s = input.readLine()) != null) {
				s1 += s + "\n";
			}
			System.out.println("文件内容：");
			System.out.println(s1);
			input.close();
			s1 += content;
		
			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			output.write(s1);
			output.close();
		} catch (Exception e) {
		   e.printStackTrace();
		}
		return true;
	}
	
	public static boolean AppendToFile(String fileName, String content)
	{
		return write(fileName, content, "encoding", 0);
	}
	
	public static boolean Wreathe(String fileName, String content)
	{
		return write(fileName, content, "encoding", 1);
	}
	
	public static void main (String s[]){
		FileIO.AppendToFile("D:/1.txt", "中华人民共和国");
	}
}
